package com.supor.aiot.mine.ui.ips;

import android.annotation.SuppressLint;
import android.app.Application;

import com.android.baseconfig.common.utils.Logc;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.mine.api.IpsImpl;
import com.supor.aiot.mine.bean.IpsBean;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

public class IpsListViewModel extends BaseViewModel {

    private MutableLiveData<Result> ipsListData = new MutableLiveData<>();
    private MutableLiveData<Result> deleteResult = new MutableLiveData<>();
    private MutableLiveData<String> loadMoreData = new MutableLiveData<>();
    private List<IpsBean> ipsList;
    int page = 1;
    int limit = 10;


    public IpsListViewModel(@NonNull Application application) {
        super(application);
        ipsList = new ArrayList<>();
    }

    public MutableLiveData<Result> getIpsListData() {
        return ipsListData;
    }

    public List<IpsBean> getIpsList() {
        return ipsList;
    }

    public MutableLiveData<Result> getDeleteResult() {
        return deleteResult;
    }

    public MutableLiveData<String> getLoadMoreData() {
        return loadMoreData;
    }

    @SuppressLint("CheckResult")
    public void ipsList(boolean loadMore) {
        if (loadMore) {
            page++;
        } else {
            page = 1;
            ipsList = new ArrayList<>();
        }
        IpsImpl.getInstance().getIpsList(page, limit).subscribe(result -> {
            if (result.isSuccess()) {
                ipsList.addAll(result.data.rows);
                ipsListData.setValue(new Result.Success(result.data));
                if (result.data.rows.size() < limit || page == result.data.allpages) {
                    loadMoreData.setValue(Constants.Value.CANCEL);
                }
            } else {
                ipsListData.setValue(new Result.Error("获取创意列表失败"));
            }
        }, throwable -> {
            Logc.e("获取创意列表失败: " + throwable.getMessage());
            ipsListData.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    @SuppressLint("CheckResult")
    public void deleteIps(IpsBean ipsBean, int position) {
        IpsImpl.getInstance().deleteIps(ipsBean.ipsId).subscribe(result -> {
            if (result.isSuccess()) {
                deleteResult.setValue(new Result.Success(position));
            } else {
                deleteResult.setValue(new Result.Error("删除创意失败"));
            }
        }, throwable -> {
            Logc.e("删除创意失败: " + throwable.getMessage());
            deleteResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }
}
